package com.ruoyi.project.mobile.user;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.RFactory;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.system.coinrecord.domain.HaoqiCoinRecord;
import com.ruoyi.project.system.coinrecord.dto.HaoqiCoinRecordDto;
import com.ruoyi.project.system.coinrecord.service.IHaoqiCoinRecordService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.sign.domain.MemberSign;
import com.ruoyi.project.system.sign.service.IMemberSignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * 功能：
 *
 * @author：dell
 * @create：2020/6/29 21:15
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@RestController
@RequestMapping("/api/coin")
public class ApiHaoqiCoinController extends BaseController {

	@Autowired
	private IHaoqiCoinRecordService haoqiCoinRecordService;

	@Autowired
	private IMemberService memberService;

	@Autowired
    private IMemberSignService memberSignService;

	/**
	 * 查询积分数量
	 * @param uid
	 * @return
	 */
	@GetMapping
	public R haoqiCoinNum(@RequestParam String uid){
		Member member = this.memberService.selectMemberById(uid);
		if(member==null){
			return R.error("用户不存在");
		}
        HashMap<String, Object> map = new HashMap<>();
        map.put("haoqiCoin",member.getHaoqiCoin());
        map.put("historyTotalCoin",member.getHistoryTotalCoin());
		return RFactory.generateR(map);
	}

    /**
     * 查询积分明细
     * @param uid
     * @return
     */
    @GetMapping("/coinDetailed")
    public R coinDetailed(@RequestParam String uid){

        Member member = this.memberService.selectMemberById(uid);
        if(member==null){
            return R.error("用户不存在");
        }
        startPage();
        HaoqiCoinRecord haoqiCoinRecord = new HaoqiCoinRecord();
        haoqiCoinRecord.setType(2);
        haoqiCoinRecord.setMemberId(uid);
        List<HaoqiCoinRecordDto> haoqiCoinRecords = this.haoqiCoinRecordService.selectHaoqiCoinRecordList(haoqiCoinRecord);
        return RFactory.generateR(getDataTable(haoqiCoinRecords));
    }

	/**
	 * 查询支出列表
	 * @param uid
	 * @return
	 */
	@GetMapping("/expenditure")
	public R haoqiCoinExpenditure(@RequestParam String uid){

		Member member = this.memberService.selectMemberById(uid);
		if(member==null){
			return R.error("用户不存在");
		}
        startPage();
		HaoqiCoinRecord haoqiCoinRecord = new HaoqiCoinRecord();
		haoqiCoinRecord.setType(1);
		haoqiCoinRecord.setMemberId(uid);
		List<HaoqiCoinRecordDto> haoqiCoinRecords = this.haoqiCoinRecordService.selectHaoqiCoinRecordList(haoqiCoinRecord);
		return RFactory.generateR(getDataTable(haoqiCoinRecords));
	}

	/**
	 * 查询收入列表
	 * @param uid
	 * @return
	 */
	@GetMapping("/income")
	public R haoqiCoinIncome(@RequestParam String uid){

		Member member = this.memberService.selectMemberById(uid);
		if(member==null){
			return R.error("用户不存在");
		}
        startPage();
		HaoqiCoinRecord haoqiCoinRecord = new HaoqiCoinRecord();
		haoqiCoinRecord.setType(0);
		haoqiCoinRecord.setMemberId(uid);
		List<HaoqiCoinRecordDto> haoqiCoinRecords = this.haoqiCoinRecordService.selectHaoqiCoinRecordList(haoqiCoinRecord);
		return RFactory.generateR(getDataTable(haoqiCoinRecords));
	}


	/**
	 * 提现
	 * @param haoqiCoinRecord
	 * @return
	 */
	@PostMapping("/withdrawal")
	@Transactional
	public R haoqiCoinWithdrawal(@RequestBody HaoqiCoinRecord haoqiCoinRecord){
		Member member = this.memberService.selectMemberById(haoqiCoinRecord.getMemberId());
		if(member.getHaoqiCoin().compareTo(haoqiCoinRecord.getNum())==-1){
			return R.error("余额不足");
		}

		haoqiCoinRecord.setType(1);
		haoqiCoinRecord.setStatus(0);
		haoqiCoinRecord.setCreated(DateUtils.getNowDate());
		this.haoqiCoinRecordService.insertHaoqiCoinRecord(haoqiCoinRecord);
		//修改个人余额
		Member update = new Member();
		update.setId(member.getId());
		update.setHaoqiCoin(member.getHaoqiCoin().subtract(haoqiCoinRecord.getNum()));
		this.memberService.updateMember(update);
		return R.ok();
	}

    /**
     * 查询签到情况
     * @param uid
     * @return
     */
    @GetMapping("/sign")
    public R memberSign(@RequestParam String uid){
        MemberSign oldSign = this.memberSignService.selectMemberSignById(uid);
        HashMap<String, Object> map = new HashMap<>();
        if(oldSign==null){
            MemberSign memberSign = new MemberSign();
            memberSign.setContinuity(0);
            memberSign.setSumCoin(new BigDecimal(0));
            memberSign.setTotal(0);
            memberSign.setId(uid);
            this.memberSignService.insertMemberSign(memberSign);
            map.put("sign",memberSign);
            map.put("today",0);
            map.put("continuity",0);
            map.put("nowDay",0);
            return RFactory.generateR(map);
        }
        map.put("sign",oldSign);
        if(oldSign.getUpdateTime()!=null){
            String updateTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, oldSign.getUpdateTime());
            String nowData = DateUtils.getDate();
            map.put("today",updateTime.equals(nowData)?1:0);
            if(DateUtils.IsYesterday(oldSign.getUpdateTime())||DateUtils.IsToday(oldSign.getUpdateTime())){
                map.put("continuity",oldSign.getContinuity());
                map.put("nowDay",oldSign.getContinuity()%7);
            }else{
                map.put("continuity",0);
                map.put("nowDay",0);
            }
        }else{
            map.put("today",0);
            map.put("continuity",0);
            map.put("nowDay",0);
        }
        return RFactory.generateR(map);
    }

    /**
     * 用户签到
     * @param memberSign
     * @return
     */
    @PostMapping("/userSign")
    @Transactional
    public R sign(@RequestBody MemberSign memberSign){
        //查询用户签到信息
        MemberSign sign = this.memberSignService.selectMemberSignById(memberSign.getId());

        memberSign.setTotal(sign.getTotal()+1);
        memberSign.setUpdateTime(DateUtils.getNowDate());
        if(sign.getUpdateTime()!=null){
            //判断用户今天是否已经签到
            if(DateUtils.IsToday(sign.getUpdateTime())){
                return R.error("请勿重复签到");
            }
            //判断最新签到时间是不是昨天
            memberSign.setContinuity(DateUtils.IsYesterday(sign.getUpdateTime())?sign.getContinuity()+1:1);
        }else {
            memberSign.setContinuity(1);
        }
        //累计获取积分
        BigDecimal coin = new BigDecimal(0);
        coin=coin.add(new BigDecimal(10));
        memberSign.setSumCoin(sign.getSumCoin().add(coin));

        this.memberSignService.updateMemberSign(memberSign);
        //生成积分记录
        HaoqiCoinRecord hondaCoinRecord = new HaoqiCoinRecord();
        hondaCoinRecord.setNum(coin);
        hondaCoinRecord.setCreated(DateUtils.getNowDate());
        hondaCoinRecord.setStatus(1);
        hondaCoinRecord.setType(2);
        hondaCoinRecord.setMemberId(memberSign.getId());
        hondaCoinRecord.setGetType(2);
        this.haoqiCoinRecordService.insertHaoqiCoinRecord(hondaCoinRecord);

        //用户积分变更
        Member member = this.memberService.selectMemberById(memberSign.getId());

        Member update = new Member();
        update.setId(member.getId());
        update.setHaoqiCoin(member.getHaoqiCoin().add(coin));
        update.setHistoryTotalCoin(member.getHistoryTotalCoin().add(coin));
        this.memberService.updateMember(update);

        return R.ok();
    }

}
